package server.db;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.sql.*;

public class DBSource {
    private static ComboPooledDataSource dataSource = null;
    private final static String dbname = "shop";//数据库名称
    private final static String password = "1809227959";

    private DBSource() {
    }

    public static DataSource getDataSource() {
        if (dataSource == null) {
            System.out.println("新建database");
            try {
                dataSource = new ComboPooledDataSource();
                dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
                dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/" + dbname + "?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8");
                dataSource.setUser("root");
                dataSource.setPassword(password);
                dataSource.setAcquireIncrement(5); //当数据库中连接数不足时，一次向数据库中申请多少个连接
                dataSource.setInitialPoolSize(10); //初始化的连接数量
                dataSource.setMinPoolSize(5); //最小连接数
                dataSource.setMaxPoolSize(20); //最大连接数
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            } catch (Exception e) {
                System.out.println("生成数据库连接池错误");
                e.printStackTrace();
            }
        }
        return dataSource;
    }

    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = getDataSource().getConnection();
        } catch (SQLException e) {
            System.out.println("获取connection失败");
        }
        return connection;
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (connection != null) {
                connection.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet) {
        try {
            if (connection != null) {
                connection.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
